package org.ala.distributed_transaction_commons.communication.coordinator;

import org.ala.distributed_transaction_commons.communication.AbstractActionExector;
import org.ala.distributed_transaction_commons.communication.Message;
import org.ala.distributed_transaction_commons.communication.Message.MessageContent;
import org.ala.distributed_transaction_commons.communication.coordinator.actions.BeginAction;
import org.ala.distributed_transaction_commons.communication.coordinator.actions.CanCommitAction;
import org.ala.distributed_transaction_commons.communication.coordinator.actions.CommitedAction;
import org.ala.distributed_transaction_commons.communication.coordinator.actions.PreCommitAction;
import org.ala.distributed_transaction_commons.communication.coordinator.actions.RollbackAction;
import org.springframework.beans.factory.InitializingBean;


/**
 * 发送给协调者的action执行器
 * <p>	这里都是redis操作，姑且不用线程池
 *
 * @author 骆毅(ala)
 * @date 2024年2月18日
 */
public class CoordinatorActionExector extends AbstractActionExector implements InitializingBean {

	
	protected BeginAction beginAction;
	protected CanCommitAction canCommitAction;
	protected PreCommitAction preCommitAction;
	protected CommitedAction commitedAction;
	protected RollbackAction rollbackAction;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		//	初始化action holder
		beginAction = new BeginAction();
		canCommitAction = new CanCommitAction(); 
		preCommitAction = new PreCommitAction();
		commitedAction = new CommitedAction();
		rollbackAction = new RollbackAction();
		
		appendAction(beginAction);
		appendAction(canCommitAction);
		appendAction(preCommitAction);
		appendAction(commitedAction);
		appendAction(rollbackAction);
	}
	
	
	/**
	 * 单独执行beginAction
	 */
	public void doBegin(String biz, String txId) {
		MessageContent mc = new MessageContent("to_coordinator", Message.MSG_TYPE_TO_COORDINATOR_BEGIN, biz, txId, null);
		canCommitAction.execute(mc);
	}
	/**
	 * 单独执行canCommitAction
	 */
	public void doCanCommit(String biz, String txId) {
		MessageContent mc = new MessageContent("to_coordinator", Message.MSG_TYPE_TO_COORDINATOR_CAN_COMMIT, biz, txId, null);
		canCommitAction.execute(mc);
	}
	/**
	 * 单独执行preCommitAction
	 */
	public void doPreCommit(String biz, String txId) {
		MessageContent mc = new MessageContent("to_coordinator", Message.MSG_TYPE_TO_COORDINATOR_PRE_COMMIT, biz, txId, null);
		preCommitAction.execute(mc);
	}
	/**
	 * 单独执行commited
	 */
	public void doCommited(String biz, String txId) {
		MessageContent mc = new MessageContent("to_coordinator", Message.MSG_TYPE_TO_COORDINATOR_COMMITED, biz, txId, null);
		commitedAction.execute(mc);
	}
	
}
